package com.jiyinit.web.core.video.manager;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.video.dto.IconUserRequest;
import com.jiyinit.web.core.video.dto.MobileRoleRequest;
import com.jiyinit.web.core.video.dto.MroleIconRequest;
import com.jiyinit.web.core.video.entity.TabCoreIconMainEntity;
import com.jiyinit.web.core.video.entity.TabCoreMobileRoleEntity;
import com.jiyinit.web.core.video.entity.TabCoreMroleIconEntity;
import com.jiyinit.web.core.video.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by user1 on 2018/12/19.
 */
@Controller
@RequestMapping(value = "/outsider")
public class OutsiderRoleController {

    private static Logger logger = LoggerFactory.getLogger(OutsiderRoleController.class);

    @Resource(name = "core.mobileRoleServiceImpl")
    private MobileRoleServiceImpl service;

    @Resource(name = "core.mroleIconServiceImpl")
    private MroleIconServiceImpl roleIconService;

    @Resource(name = "core.iconUserServiceImpl")
    private IconUserServiceImpl iconUserService;

    @Resource(name = "core.iconMainServiceImpl")
    private IconMainServiceImpl iconMainService;

    /**
     * 跳转查询页面
     * @return
     */
    @RequestMapping(value = "mobileRoleList",method = RequestMethod.GET)
    private String list(){
        return "/mobile/outsiderRoleList";
    }

    /**
     * 跳转添加页面
     * @return
     */
    @RequestMapping(value = "add",method = RequestMethod.GET)
    private String toadd(){
        return "/mobile/mobileRoleAdd";
    }

    /**
     * 跳到修改页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/edit")
    public String edit(Model model, HttpServletRequest request, Integer id) {
        TabCoreMobileRoleEntity entity= service.findOne(id);
        request.setAttribute("mobileIconMain", entity);
        return "/mobile/mobileRoleEdit";
    }

    /**
     * 分页查询
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getPageRows")
    public PagingResult<TabCoreMobileRoleEntity> getPageRows(HttpServletRequest req, MobileRoleRequest mobileRoleRequest){
        logger.info("转换为obj之后的参数: {}", mobileRoleRequest.toString());
        mobileRoleRequest.setLimit(10);
        mobileRoleRequest.setCreateUid(UserUtil.getCurrentUser().getUserId());
        PagingResult<TabCoreMobileRoleEntity> pag = service.findForPage(mobileRoleRequest);
        return pag;
    }

    /**
     * 添加
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/toAdd", method= RequestMethod.POST)
    public ResponseEntity<ResponseDto> add(HttpServletRequest req, TabCoreMobileRoleEntity entity){
        logger.info("转换为obj之后的参数: {}", entity.toString());
        int i = 0;
        if(!Check.isNullObj(entity)){
            entity.setCreateUid(UserUtil.getCurrentUser().getUserId());
            i = service.add(entity);
            logger.info("添加之后的json串:{}", JsonEntityTransform.object2Json(entity));
        }
        if (i>0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("添加失败"),HttpStatus.OK);
    }

    /**
     * 修改
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update", method=RequestMethod.POST)
    public ResponseEntity<ResponseDto> update(HttpServletRequest req, TabCoreMobileRoleEntity entity){
        logger.info("转换为obj之后的参数: {}", entity.toString());
        int i = 0;
        if(!Check.isNullObj(entity)){
            i = service.update(entity);
            logger.info("更新之后的json串:{}", JsonEntityTransform.object2Json(entity));
        }
        if (i>0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""),HttpStatus.OK);
    }

    /**
     * 删除
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method=RequestMethod.POST)
    public ResponseEntity<ResponseDto> delete(HttpServletRequest req, Integer ids) {
        int num=service.delete(ids);
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK("操作成功"), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("操作失败"), HttpStatus.OK);
    }

    /**
     * 权限树页面
     * @param req
     * @return
     */
    @RequestMapping(value = "/roleTree", method = RequestMethod.GET)
    public String toRoleTree(HttpServletRequest req) {
        String roleId = req.getParameter("roleId");
        req.setAttribute("roleId", roleId);
        req.setAttribute("userId", UserUtil.getCurrentUser().getUserId());
        req.setAttribute("queryUrl", "outsider/roleTree");
        req.setAttribute("updateUrl", "outsider/updateResourceByRoleId");
        return "mobile/outsiderRoleTreeUpdate";
    }

    /**
     * 查询该用户拥有的功能
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/roleTree", method = RequestMethod.POST)
    public ResponseEntity<ResponseDto> getRoleTree(HttpServletRequest req, IconUserRequest request, Integer roleId) {
        request.setUserId(UserUtil.getCurrentUser().getUserId());
        List<String> iconIdArray = iconUserService.findIconListByUserId(request.getUserId());
        //1.该用户拥有的所有权限
        String[] allIcon = iconIdArray.toArray(new String[iconIdArray.size()]);

        MroleIconRequest roleIconRequest = new MroleIconRequest();
        roleIconRequest.setRoleId(roleId);
        //2.查询目标角色拥有的权限
        PagingResult<TabCoreMroleIconEntity> result = roleIconService.findForPage(roleIconRequest);
        String[] iconIds = getIconIds(result);
        String[] notInIds = null;
        if(!Check.isNullObject(allIcon)){
            List<TabCoreIconMainEntity> iconList = new ArrayList<>();
            if(!Check.isNullObject(iconIds)){
                iconList = iconMainService.findInIds(iconIds);
                convert(iconList);
                notInIds = removeIdenticalIds(allIcon, iconIds);
            }else{
                notInIds = allIcon;
            }
            if(!Check.isNullObject(notInIds)){
                List<TabCoreIconMainEntity> noSelected = iconMainService.findInIds(notInIds);
                iconList.addAll(noSelected);
            }
            if(Check.isNullCollection(iconList)){
                return new ResponseEntity<>(ResponseDto.responseFail("当前用户无操作权限"), HttpStatus.OK);
            }
            List<Map<String, Object>> items = new ArrayList<>();
            for (TabCoreIconMainEntity iconObj : iconList) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", iconObj.getId());
                //map.put("pId", roleResourceVo.getParentId());
                map.put("name", iconObj.getIconName());
                map.put("open", false);
                if(iconObj.getIsSelected().equals("1")){
                    map.put("checked", true);
                }
                items.add(map);
            }
            return new ResponseEntity<>(ResponseDto.responseOK(items), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("当前用户无操作权限"), HttpStatus.OK);
    }
    public String[] removeInvalid(String[] split, String[] userIcons){
        ArrayList<String> array = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            Child:
            for (int j = 0; j < userIcons.length; j++) {
                if(split[i].equals(userIcons[j])){
                    array.add(userIcons[j]);
                    break Child;
                }
            }
        }
        return array.toArray(new String[array.size()]);
    }
    public String[] removeIdenticalIds(String[] main, String[] same){
        ArrayList<String> newArray = new ArrayList<>();
        HashSet<String> str = new HashSet<>();
        str.addAll(Arrays.asList(same));
        for (int i = 0; i < main.length; i++) {
            if(!str.contains(main[i])){
                newArray.add(main[i]);
            }
        }
        return newArray.toArray(new String[newArray.size()]);
    }
    public void convert(List<TabCoreIconMainEntity> iconList){
        for(TabCoreIconMainEntity obj : iconList){
            obj.setIsSelected("1");
        }
    }
    public String[] getIconIds (PagingResult<TabCoreMroleIconEntity> page) {
        List<TabCoreMroleIconEntity> rows = page.getRows();
        if(Check.isNullCollection(rows)){
            return  null;
        }
        ArrayList<String> strs = new ArrayList<>();
        for (int i = 0; i < rows.size(); i++) {
            strs.add(rows.get(i).getIconId()+"");
        }
        return strs.toArray(new String[strs.size()]);
    }

    /**
     * 分配权限
     * @param req
     * @return
     */
    @RequestMapping(value = "/updateResourceByRoleId")
    public ResponseEntity<ResponseDto> updateResourceByRoleId(HttpServletRequest req, Integer roleId, Integer[] resourceIds) {
        if(Check.isNullObject(resourceIds)){
            return new ResponseEntity<>(ResponseDto.responseFail("权限不能为空"), HttpStatus.OK);
        }
        if(Check.isNullObj(roleId)){
            return new ResponseEntity<>(ResponseDto.responseFail("参数不能为空"), HttpStatus.OK);
        }
        List<TabCoreMroleIconEntity> roleIcons = new ArrayList<>();
        for (Integer resourceId : resourceIds) {
            TabCoreMroleIconEntity roleIconEntity = new TabCoreMroleIconEntity();
            roleIconEntity.setRoleId(roleId);
            roleIconEntity.setIconId(resourceId);
            roleIcons.add(roleIconEntity);
        }
        int delNum = roleIconService.deleteByRoleId(roleId);
        int addNum = roleIconService.addRoleIconByList(roleIcons);
        logger.info("本次共删除{}条功能, 共新增{}条功能====================================", delNum, addNum);

        if(addNum > 0){
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("未知错误"), HttpStatus.OK);
    }


}
